#!/usr/bin/python

import mosquitto
import time
import os
import _mysql

execfile("/opt/python/includes/mysql.py")

def on_connect(mosq, rc):
    if rc == 0:
        print("Connected OK")

def on_disconnect(rc):
    print("Disconnected.")

def on_message(mosq, msg):
    print("Got message: "+msg.payload+" from topic "+msg.topic+" at "+str(time.time()))
    type=msg.topic.split("/")[0]
    name=msg.topic.split("/")[1]
    sensor=getSensor(name, type, db)
    db.query("INSERT INTO sensor_data VALUES ( "+sensor+" , "+msg.payload+", "+str(time.time())+" ) ")

def on_subscribe(mosq, mid, rc):
    print("Subscribed ok")

client = mosquitto.Mosquitto("client-"+os.uname()[1]+"-"+str(os.getpid()))
print("Created client")
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
print("Defined callbacks")
db=getDBCon()

client.connect("KitchenPI.home")
client.subscribe("temp/+", 1)
client.subscribe("switch/+", 1)

while client.loop()==0:
    time.sleep(0.1)
